package com.tree.thrive.business.global.net;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.InetAddress;

@Slf4j
public class NetworkUtil {
    public static final String UNKNOWN = "unknown";

    public static String getRemoteIp() {
        return getRemoteIp(RequestHolder.getRequestFacade());
    }

    public static String getRemoteIp(HttpServletRequest request) {
        try {
            return NetworkUtil.getIpAddress(request);
        } catch (Exception e) {
            log.error("获取IP，异常，{}", e.getMessage(), e);
            return UNKNOWN;
        }
    }

    private static String getIpAddress(HttpServletRequest request) throws IOException {
        String ip = request.getHeader("X-Forwarded-For");
        log.info("X-Forwarded-For，获取IP={}", ip);

        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
                log.info("Proxy-Client-IP，获取IP={}", ip);
            }
            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
                log.info("WL-Proxy-Client-IP，获取IP={}", ip);
            }
            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
                log.info("HTTP_CLIENT_IP，获取IP={}", ip);
            }
            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                log.info("HTTP_X_FORWARDED_FOR，获取IP={}", ip);
            }
            if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                log.info("getRemoteAddr，获取IP={}", ip);
            }
        } else if (ip.contains(",")) {
            String[] ips = ip.split(",");
            for (String ipTmp : ips) {
                if (UNKNOWN.equalsIgnoreCase(ipTmp)) {
                    continue;
                }
                return ipTmp;
            }
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {//win7下使用localhost访问时没有经过路由
            return InetAddress.getLocalHost().getHostAddress();
        }
        if (StringUtils.isBlank(ip)) {
            return UNKNOWN;
        }

        log.info("获取IP={}", ip);
        return ip;
    }

}  